import os, sys, time, yaml

from ivic.webfarm import WebFarmUtils
from ivic.webfarm.WorkNode import *
from ivic.core import Logging
logger = Logging.get_logger('ivic.webfarm.Server')

class WebFarmServer(object):
    
    def __init__(self,config = None):
        
        self.vm_uuid = ""
        self.webfarm_vip = ""
        self.nodes_mgr = None
        
        try:
            self.vm_uuid = WebFarmUtils.get_vm_uuid(config['vm_yaml'])
            if self.vm_uuid == 'not-set': raise
            
            self.webfarm_vip = WebFarmUtils.get_webfarm_vip()
            if self.webfarm_vip == '': raise
            
            self.nodes_mgr = WorkNodeMgr(self.vm_uuid,self.webfarm_vip)
            if not self.nodes_mgr: raise 
        except Exception,ex:
            logger.error("%s:%s" % (sys._getframe().f_code.co_name, ex))
            sys.exit()
        
    def add_nodes(self,node_list):
        """
        Add additional nodes to load balancing facility: ipvs
        argument:
            node_list: such as ['10.xxx.xxx.xxx','10.xxx.xxx.xxx']
        return:
            True: if the operation results in success
            False: else
        """
        try:
            logger.debug('remote call of add nodes: %s' % node_list)
            rst = self.nodes_mgr.batch_add_ips(self.webfarm_vip,node_list)
            return rst
        except Exception,ex:
            logger.error("%s:%s" % (sys._getframe().f_code.co_name, ex))
            return False
    
    def remove_k(self,k=0):
        """
        Remove the top k lightest load weight nodes from ipvs.
        argument:
            k: Number of nodes to be removed
        return:
            #list: a list of ips whose corresponding nodes has been removed.
            string: space joins ips string.
        warning:
            the number of nodes removed may be smaller than requried.
        """
        try:
            ds = self.nodes_mgr.remove_top_k(k)
            return ' '.join(ds)
        except Exception,ex:
            logger.error("%s:%s" % (sys._getframe().f_code.co_name, ex))
            return ' '

